//
//  CMSChartsContainerView.m
//  CMSCharts
//
//  Created by symbio on 2023/3/8.
//

#import "CMSChartsContainerView.h"
#import "CMSChartsContentView.h"
#import <CMSFoundation/CMSFoundation.h>
#import <CMSUIKit/CMSUIKit.h>
#import <Masonry/Masonry.h>
#import "CMSCharts-Swift.h"

@interface CMSChartsContainerView ()

/// 混合主股票蜡烛图
@property (nonatomic, strong) CMSChartsContentView *combineLineStickChart;
/// 混合副图指标
@property (nonatomic, strong) CMSChartsContentView *firstSubsidiaryChartView;
@property (nonatomic, strong) CMSChartsContentView *secondSubsidiaryChartView;
@property (nonatomic, strong) CMSChartsContentView *thirdSubsidiaryChartView;
@property (nonatomic, strong) CMSChartsMarkerLink *markerLink;

@end

@implementation CMSChartsContainerView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        self.viewModel = [[CMSChartsViewModel alloc] init];
//        [self addObserver];
        self.markerLink = [[CMSChartsMarkerLink alloc] initWithCharts:@[] bottomMarkerChart:nil];
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    [self setupUIMainDailyKLine];
}

- (void)updateUI {
    [self.combineLineStickChart removeFromSuperview];
    [self.firstSubsidiaryChartView removeFromSuperview];
    [self.secondSubsidiaryChartView removeFromSuperview];
    [self.thirdSubsidiaryChartView removeFromSuperview];

    if (self.containerModels.count <= 1) {
        [self addSubview:self.combineLineStickChart];
        [self.combineLineStickChart mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.height.mas_equalTo(500);
        }];
    } else if (self.containerModels.count <= 2) {
        [self addSubview:self.combineLineStickChart];
        [self.combineLineStickChart mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.height.mas_equalTo(400);
        }];
        [self addSubview:self.firstSubsidiaryChartView];
        [self.firstSubsidiaryChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.combineLineStickChart.mas_bottom);
            make.height.mas_equalTo(100);
        }];
    } else if (self.containerModels.count <= 3) {
        [self addSubview:self.combineLineStickChart];
        [self.combineLineStickChart mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.height.mas_equalTo(300);
        }];
        [self addSubview:self.firstSubsidiaryChartView];
        [self.firstSubsidiaryChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.combineLineStickChart.mas_bottom);
            make.height.mas_equalTo(100);
        }];
        [self addSubview:self.secondSubsidiaryChartView];
        [self.secondSubsidiaryChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.firstSubsidiaryChartView.mas_bottom);
            make.height.mas_equalTo(100);
        }];
    } else if (self.containerModels.count <= 4) {
        [self addSubview:self.combineLineStickChart];
        [self.combineLineStickChart mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.height.mas_equalTo(200);
        }];
        [self addSubview:self.firstSubsidiaryChartView];
        [self.firstSubsidiaryChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.combineLineStickChart.mas_bottom);
            make.height.mas_equalTo(100);
        }];
        [self addSubview:self.secondSubsidiaryChartView];
        [self.secondSubsidiaryChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.firstSubsidiaryChartView.mas_bottom);
            make.height.mas_equalTo(100);
        }];
        [self addSubview:self.thirdSubsidiaryChartView];
        [self.thirdSubsidiaryChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.secondSubsidiaryChartView.mas_bottom);
            make.height.mas_equalTo(100);
        }];
    }

}


- (void)setContainerModels:(NSArray<CMSChartsContentModel *> *)containerModels {
    _containerModels = containerModels;
    
    [self updateUI];
    
    if (self.containerModels.count >= 4) {
        self.thirdSubsidiaryChartView.model = self.containerModels[3];
    }
    if (self.containerModels.count >= 3) {
        self.secondSubsidiaryChartView.model = self.containerModels[2];
    }
    if (self.containerModels.count >= 2) {
        self.firstSubsidiaryChartView.model = self.containerModels[1];
    }
    if (self.containerModels.count >= 1) {
        self.combineLineStickChart.model = self.containerModels[0];
    }
    if (self.containerModels.count == 0) {
        CMSChartsContentModel *model = [[CMSChartsContentModel alloc] init];
        self.combineLineStickChart.model = model;
    }
    
    self.markerLink.charts = [self allChartViews];
    self.markerLink.bottomMarkerChart = [self allChartViews].lastObject;
}

#pragma mark - ChartViewDelegate

/// 同步手势
/// - Parameter chartView: chartView description
- (void)updateTouchForTransform:(CGAffineTransform)transform {
    [self syncTouchForTransform:transform chartView:self.combineLineStickChart.chartsView];
    [self syncTouchForTransform:transform chartView:self.firstSubsidiaryChartView.chartsView];
    [self syncTouchForTransform:transform chartView:self.secondSubsidiaryChartView.chartsView];
    [self syncTouchForTransform:transform chartView:self.thirdSubsidiaryChartView.chartsView];
}


- (void)syncTouchForTransform:(CGAffineTransform)transform chartView:(CombinedChartView *)chartView {
    [chartView.viewPortHandler refreshWithNewMatrix:transform chart:chartView invalidate:true];
}

#pragma mark - 混合副图指标

- (CMSChartsContentView *)firstSubsidiaryChartView {
    if (!_firstSubsidiaryChartView) {
        _firstSubsidiaryChartView = [[CMSChartsContentView alloc] init];
        [self setupContainerView:_firstSubsidiaryChartView idx:1];
    }
    return _firstSubsidiaryChartView;
}

- (CMSChartsContentView *)secondSubsidiaryChartView {
    if (!_secondSubsidiaryChartView) {
        _secondSubsidiaryChartView = [[CMSChartsContentView alloc] init];
        [self setupContainerView:_secondSubsidiaryChartView idx:2];
    }
    return _secondSubsidiaryChartView;
}

- (CMSChartsContentView *)thirdSubsidiaryChartView {
    if (!_thirdSubsidiaryChartView) {
        _thirdSubsidiaryChartView = [[CMSChartsContentView alloc] init];
        [self setupContainerView:_thirdSubsidiaryChartView idx:3];
    }
    return _thirdSubsidiaryChartView;
}

#pragma mark - K线主视图

- (void)setupUIMainDailyKLine {
//    [self addSubview:self.combineLineStickChart];
//    [self.combineLineStickChart mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.equalTo(self);
//        make.top.equalTo(self.headerView.mas_bottom);
//    }];
}

- (CMSChartsContentView *)combineLineStickChart {
    if (!_combineLineStickChart) {
        _combineLineStickChart = [[CMSChartsContentView alloc] init];
        [self setupContainerView:_combineLineStickChart idx:0];
    }
    return _combineLineStickChart;
}


- (void)setupContainerView:(CMSChartsContentView *)containerView idx:(NSInteger)idx {
    @weakify(self);
    @weakify(containerView);
    containerView.updateTouchBlock = ^(CGAffineTransform transform) {
        @strongify(self);
        [self updateTouchForTransform:transform];
    };
    containerView.didSelectItemBlock = ^(NSInteger index, NSString * _Nonnull title) {
        @strongify(self);
        @strongify(containerView);
        NSLog(@"%@-点击的第%ld个按钮", title, index);
//        [self popActionsWithIdx:idx];
        if (self.didSelectTagBlock) {
            self.didSelectTagBlock(containerView.chartsView, idx, index, title);
        }
    };
    containerView.chartValueSelectedBlock = ^(ChartViewBase * _Nonnull chartView, ChartDataEntry * _Nonnull entry, ChartHighlight * _Nonnull highlight) {
        @strongify(self);
        
        CGPoint point = [chartView convertPoint:highlight.touchPoint toView:self.combineLineStickChart.chartsView];
        ChartHighlight *mainHighlight = [self.combineLineStickChart.chartsView getHighlightByTouchPoint:point];

        for (CombinedChartView *chart in [self allChartViews]) {
            if (chartView == self.combineLineStickChart.chartsView && chart == chartView) {
                continue;
            }

            CGPoint tempPoint = [chartView convertPoint:highlight.touchPoint toView:chart];
            ChartHighlight *tempHighlight = [chart getHighlightByTouchPoint:tempPoint];
            if (tempHighlight == nil) {
                tempHighlight = [[ChartHighlight alloc] initWithX:highlight.x dataSetIndex:0 stackIndex:0];
            }
            tempHighlight.touchPoint = CGPointMake(mainHighlight.xPx, tempPoint.y);
            tempHighlight.fake = YES;
            chart.lastHighlighted = tempHighlight;
            chart.highlightShowing = YES;
            [chart highlightValue:tempHighlight callDelegate:false];
        }
    };
    containerView.chartValueNothingSelectedBlock = ^(ChartViewBase * _Nonnull chartView) {
        @strongify(self);
        for (CombinedChartView *chart in [self allChartViews]) {
            if (chart == chartView) {
                continue;
            }
            chart.highlightShowing = NO;
            [chart highlightValue:nil callDelegate:false];
        }
    };
    containerView.chartViewCanHighlight = ^BOOL(ChartViewBase * _Nonnull chartView, UIGestureRecognizer * _Nonnull recognizer) {
        @strongify(self);
        if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]) {
            return YES;
        }
        if (self.combineLineStickChart.chartsView == chartView) {
            return YES;
        }
        return NO;
    };
}

- (NSArray *)allChartViews {
    NSMutableArray *muarr = [NSMutableArray array];

    for (CMSChartsContentView *containerView in @[self.combineLineStickChart, self.firstSubsidiaryChartView, self.secondSubsidiaryChartView, self.thirdSubsidiaryChartView]) {
        if (containerView.superview) {
            [muarr addObject:containerView.chartsView];
        }
    }
    return muarr.copy;
}

- (void)popActionsWithIdx:(NSInteger)idx {
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"功能列表" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    if (idx == 0) {
        [controller addAction:[UIAlertAction actionWithTitle:@"叠加K线" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
    }
    [controller addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self.cms_viewController presentViewController:controller animated:YES completion:nil];
}
@end
